import { defineStore } from "pinia";

export const useScanStore = defineStore(
	"scan",
	() => {
		const scanRes = reactive({});

		// 扫码数据 缺件列表 存储
		const missingState = reactive({
			mainOrderNumber: null,
			list: [],
			boxNumber: 0,
		});

		// 取得扫描数据
		const getScanRes = (id, oneOff?: boolean) => {
			if (!scanRes[id]) {
				console.log("暂无存储扫描数据");
				return;
			}

			const res = scanRes[id];

			const isOneOff = typeof oneOff === "boolean" ? oneOff : true;

			if (oneOff) {
				removeScanRes(id);
			}
			return res;
		};

		const removeScanRes = (id) => {
			if (!scanRes[id]) {
				console.log("暂无存储扫描数据");
				return;
			}
			scanRes[id] = null;
		};

		const setScanRes = (id, value) => {
			try {
				scanRes[id] = value;
			} catch (error) {
				console.log(error);
			}
		};

		return {
			get: getScanRes,
			set: setScanRes,
			remove: removeScanRes,

			missing: {
				getMain: () => missingState.mainOrderNumber,
				getList: () => missingState.list,
				setMain: (v) => (missingState.mainOrderNumber = v),
				setList: (v) => (missingState.list = v),
				getBox: () => missingState.boxNumber,
				setBox: (v) => (missingState.boxNumber = v),
				clear: () => {
					missingState.mainOrderNumber = null;
					missingState.boxNumber = 0;
					missingState.list = [];
				},
			},
		};
	},
	{
		persist: true,
	},
);
